<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Comment as CommentType } from '@/apis/methods/comment.api'
import { PhHeart, PhArrowBendUpLeft, PhCaretDown, PhDotsThree, PhFlag } from '@phosphor-icons/vue'
import type {
  CommentItemProps,
  CommentItemEvents,
  SlotProps,
  EventHandlers,
} from './types/comment-item.types'
import { TIME_FORMATTERS } from './types/comment-item.types'

const props = withDefaults(defineProps<CommentItemProps>(), {
  replies: () => [],
  showReplies: false,
  hasMoreReplies: false,
  submitting: false,
  layout: 'default',
  responsive: true,
  showAvatar: true,
  showActions: true,
  showReplyButton: true,
  showLikeButton: true,
  showMoreButton: true,
  showTimestamp: true,
  showReplyCount: true,
  showRepliesSection: true,
  avatarSize: 'md',
  cardStyle: 'default',
  spacing: 'normal',
  enableHover: true,
  enableAnimations: true,
  enableClickOutside: true,
  enableKeyboard: true,
  customFormatTime: TIME_FORMATTERS.chinese,
})

const emit = defineEmits<CommentItemEvents>()

const replyingTo = ref<string | null>(null)
const replyContent = ref('')
const showMoreActions = ref(false)

// 事件处理函数
const handleToggleReplies = () => {
  emit('toggleReplies', props.comment.id)
}

const handleLoadMoreReplies = () => {
  emit('loadMoreReplies', props.comment.id)
}

const handleToggleLike = () => {
  emit('toggleLike', props.comment.id)
}

const handleCreateReply = (content: string, mentionedUsers: string[] = []) => {
  emit('createReply', props.comment.id, content, mentionedUsers)
  replyContent.value = ''
  replyingTo.value = null
}

const handleReportComment = () => {
  emit('reportComment', props.comment.id)
  showMoreActions.value = false
}

const handleDeleteComment = () => {
  emit('deleteComment', props.comment.id)
  showMoreActions.value = false
}

const handleReplyClick = (reply: CommentType) => {
  emit('replyClick', reply)
}

const handleAvatarClick = (author: CommentType['author']) => {
  emit('avatarClick', author)
}

const handleAuthorClick = (author: CommentType['author']) => {
  emit('authorClick', author)
}

const handleContentClick = (comment: CommentType) => {
  emit('contentClick', comment)
}

const startReply = () => {
  replyingTo.value = props.comment.id
  replyContent.value = ''
}

const cancelReply = () => {
  replyingTo.value = null
  replyContent.value = ''
}

// 格式化时间
const formatTime = (dateString: string): string => {
  // 使用自定义格式化函数或默认的中文格式化
  return props.customFormatTime
    ? props.customFormatTime(dateString)
    : TIME_FORMATTERS.chinese(dateString)
}

// 计算样式类
const avatarSizeClass = computed(() => {
  const baseClasses = props.styleConfig?.customClass || ''
  switch (props.avatarSize) {
    case 'xs':
      return `${baseClasses} w-6 h-6 text-xs`
    case 'sm':
      return `${baseClasses} w-8 h-8 text-sm`
    case 'lg':
      return `${baseClasses} w-16 h-16 text-lg`
    case 'xl':
      return `${baseClasses} w-20 h-20 text-xl`
    case '2xl':
      return `${baseClasses} w-24 h-24 text-2xl`
    default:
      return `${baseClasses} w-12 h-12 text-base`
  }
})

const spacingClass = computed(() => {
  switch (props.spacing) {
    case 'tight':
      return 'gap-2 p-3'
    case 'loose':
      return 'gap-6 p-8'
    case 'xl':
      return 'gap-8 p-12'
    default:
      return 'gap-4 p-6'
  }
})

const cardClass = computed(() => {
  const baseClasses = props.enableAnimations ? 'transition-all duration-300 ease-out' : ''
  const customClass = props.styleConfig?.customClass || ''
  const presetClass = props.styleConfig?.preset ? `preset-${props.styleConfig.preset}` : ''

  switch (props.cardStyle) {
    case 'minimal':
      return `${baseClasses} ${customClass} ${presetClass} bg-transparent border-0 p-0`
    case 'elevated':
      return `${baseClasses} ${customClass} ${presetClass} bg-base-100 rounded-3xl ${spacingClass.value} border border-base-300/20 shadow-lg hover:shadow-xl hover:-translate-y-1`
    case 'outlined':
      return `${baseClasses} ${customClass} ${presetClass} bg-transparent rounded-2xl ${spacingClass.value} border-2 border-base-300/50 hover:border-primary/50`
    case 'flat':
      return `${baseClasses} ${customClass} ${presetClass} bg-base-100/50 rounded-xl ${spacingClass.value} border-0`
    case 'glass':
      return `${baseClasses} ${customClass} ${presetClass} bg-base-100/20 backdrop-blur-md rounded-2xl ${spacingClass.value} border border-white/20 shadow-lg`
    case 'neon':
      return `${baseClasses} ${customClass} ${presetClass} bg-gradient-to-br from-primary/10 via-secondary/10 to-accent/10 rounded-2xl ${spacingClass.value} border border-primary/30 shadow-lg shadow-primary/20`
    default:
      return `${baseClasses} ${customClass} ${presetClass} bg-gradient-to-br from-base-100 to-base-200/50 rounded-2xl ${spacingClass.value} border border-base-300/30 shadow-sm hover:shadow-md hover:-translate-y-0.5`
  }
})

const layoutClass = computed(() => {
  switch (props.layout) {
    case 'compact':
      return 'flex items-start gap-2'
    case 'minimal':
      return 'flex items-center gap-2'
    case 'card':
      return 'flex flex-col gap-4'
    case 'timeline':
      return 'flex gap-4 relative'
    default:
      return 'flex gap-4'
  }
})

const repliesClass = computed(() => {
  switch (props.layout) {
    case 'compact':
      return 'ml-6 mt-2 space-y-2'
    case 'minimal':
      return 'ml-4 mt-2 space-y-1'
    case 'card':
      return 'mt-4 space-y-3'
    case 'timeline':
      return 'ml-12 mt-4 space-y-3 border-l-2 border-base-300/30 pl-4'
    default:
      return 'ml-8 mt-4 space-y-3'
  }
})

// 计算插槽参数
const slotProps = computed<SlotProps>(() => ({
  comment: props.comment,
  replies: props.replies,
  showReplies: props.showReplies,
  hasMoreReplies: props.hasMoreReplies,
  submitting: props.submitting,
  layout: props.layout,
  avatarSize: props.avatarSize,
  cardStyle: props.cardStyle,
  spacing: props.spacing,
  formatTime,
  classes: {
    avatar: avatarSizeClass.value,
    author: props.styleConfig?.customClass || '',
    content: props.styleConfig?.customClass || '',
    actions: props.styleConfig?.customClass || '',
    replies: props.styleConfig?.customClass || '',
    card: cardClass.value,
  },
}))

// 计算事件处理器
const eventHandlers = computed<EventHandlers>(() => ({
  toggleReplies: handleToggleReplies,
  loadMoreReplies: handleLoadMoreReplies,
  toggleLike: handleToggleLike,
  createReply: (parentId: string, content: string, mentionedUsers: string[]) =>
    handleCreateReply(content, mentionedUsers),
  reportComment: handleReportComment,
  deleteComment: handleDeleteComment,
  replyClick: handleReplyClick,
  startReply,
  cancelReply,
}))

// 计算自定义样式
const customStyle = computed(() => {
  const style: Record<string, string> = { ...props.customStyle }

  // 合并自定义CSS变量
  if (props.customVars) {
    Object.entries(props.customVars).forEach(([key, value]) => {
      style[`--${key}`] = value
    })
  }

  // 合并样式配置中的CSS变量
  if (props.styleConfig?.customVars) {
    Object.entries(props.styleConfig.customVars).forEach(([key, value]) => {
      style[`--${key}`] = value
    })
  }

  return style
})
</script>

<template>
  <div
    class="comment-item group"
    :class="[
      customClass,
      {
        'hover-enabled': enableHover,
        'animation-enabled': enableAnimations,
        'keyboard-enabled': enableKeyboard,
      },
    ]"
    :style="customStyle"
  >
    <!-- 主评论区域 - 完全可自定义 -->
    <div :class="cardClass">
      <slot
        name="main-content"
        v-bind="slotProps"
        :handlers="eventHandlers"
        :replying-to="replyingTo"
        :reply-content="replyContent"
        :show-more-actions="showMoreActions"
        :submitting="submitting"
      >
        <!-- 默认布局 -->
        <div :class="layoutClass">
          <!-- 头像区域 -->
          <div v-if="showAvatar" class="flex-shrink-0">
            <slot
              name="avatar"
              :author="comment.author"
              :size="avatarSize"
              :size-class="avatarSizeClass"
              :on-click="() => handleAvatarClick(comment.author)"
            >
              <div
                v-if="comment.author.avatar"
                :class="[
                  'rounded-full overflow-hidden border-2 border-base-300/50 shadow-sm cursor-pointer',
                  avatarSizeClass,
                ]"
                @click="handleAvatarClick(comment.author)"
              >
                <img
                  :src="comment.author.avatar"
                  :alt="comment.author.name"
                  class="w-full h-full object-cover"
                />
              </div>
              <div
                v-else
                :class="[
                  'bg-gradient-to-br from-primary via-primary/80 to-secondary rounded-full flex items-center justify-center text-primary-content font-semibold shadow-sm cursor-pointer',
                  avatarSizeClass,
                ]"
                @click="handleAvatarClick(comment.author)"
              >
                {{ comment.author.name.charAt(0).toUpperCase() }}
              </div>
            </slot>
          </div>

          <!-- 内容区域 -->
          <div class="flex-1 min-w-0">
            <!-- 用户信息区域 -->
            <div class="flex items-center justify-between mb-3">
              <div class="flex items-center gap-3">
                <slot
                  name="author"
                  :author="comment.author"
                  :on-click="() => handleAuthorClick(comment.author)"
                >
                  <h4
                    class="font-semibold text-base text-base-content cursor-pointer hover:text-primary transition-colors"
                    @click="handleAuthorClick(comment.author)"
                  >
                    {{ comment.author.name }}
                  </h4>
                </slot>

                <slot name="badge" :author="comment.author">
                  <!-- 用户徽章插槽 -->
                </slot>

                <slot
                  name="timestamp"
                  :timestamp="comment.createdAt"
                  :formatted-time="formatTime(comment.createdAt)"
                  v-if="showTimestamp"
                >
                  <time class="text-sm text-base-content/60">
                    {{ formatTime(comment.createdAt) }}
                  </time>
                </slot>
              </div>

              <!-- 更多操作 -->
              <div v-if="showMoreButton" class="relative">
                <slot
                  name="more-actions"
                  :comment="comment"
                  :show-more="showMoreActions"
                  :on-toggle="() => (showMoreActions = !showMoreActions)"
                  :on-report="handleReportComment"
                  :on-delete="handleDeleteComment"
                >
                  <button
                    @click="showMoreActions = !showMoreActions"
                    class="p-1 rounded-full hover:bg-base-300/50 transition-colors duration-200 opacity-0 group-hover:opacity-100"
                  >
                    <PhDotsThree :size="16" class="text-base-content/60" />
                  </button>

                  <div
                    v-if="showMoreActions"
                    class="absolute right-0 top-8 bg-base-100 rounded-xl shadow-lg border border-base-300/30 py-2 z-10 min-w-[120px]"
                  >
                    <button
                      @click="handleReportComment"
                      class="w-full px-4 py-2 text-sm text-base-content/80 hover:bg-base-200/50 flex items-center gap-2"
                    >
                      <PhFlag :size="14" />
                      举报
                    </button>
                    <button
                      @click="handleDeleteComment"
                      class="w-full px-4 py-2 text-sm text-error hover:bg-error/10 flex items-center gap-2"
                    >
                      删除
                    </button>
                  </div>
                </slot>
              </div>
            </div>

            <!-- 评论内容区域 -->
            <div class="prose prose-sm max-w-none mb-4">
              <slot
                name="content"
                :content="comment.content"
                :comment="comment"
                :on-click="() => handleContentClick(comment)"
              >
                <div
                  v-html="comment.content"
                  class="comment-content cursor-pointer hover:bg-base-200/30 rounded-lg p-2 -m-2 transition-colors"
                  @click="handleContentClick(comment)"
                ></div>
              </slot>
            </div>

            <!-- 操作按钮区域 -->
            <div v-if="showActions" class="flex items-center gap-6">
              <slot
                name="actions"
                :comment="comment"
                :show-like-button="showLikeButton"
                :show-reply-button="showReplyButton"
                :show-reply-count="showReplyCount"
                :show-replies="showReplies"
                :handlers="{
                  toggleLike: handleToggleLike,
                  startReply,
                  toggleReplies: handleToggleReplies,
                }"
              >
                <!-- 点赞按钮 -->
                <button
                  v-if="showLikeButton"
                  @click="handleToggleLike"
                  class="flex items-center gap-2 text-sm transition-all duration-200 hover:scale-105"
                  :class="
                    comment.isLiked ? 'text-red-500' : 'text-base-content/60 hover:text-red-500'
                  "
                >
                  <PhHeart
                    :size="16"
                    :class="{ 'ph-fill': comment.isLiked }"
                    class="transition-transform duration-200"
                    :style="{ transform: comment.isLiked ? 'scale(1.1)' : 'scale(1)' }"
                  />
                  <span class="font-medium">{{ comment.likes }}</span>
                </button>

                <!-- 回复按钮 -->
                <button
                  v-if="showReplyButton"
                  @click="startReply"
                  class="flex items-center gap-2 text-sm text-base-content/60 hover:text-primary transition-all duration-200 hover:scale-105"
                >
                  <PhArrowBendUpLeft :size="16" />
                  <span class="font-medium">回复</span>
                </button>

                <!-- 回复数量 -->
                <button
                  v-if="showReplyCount && comment.replyCount && comment.replyCount > 0"
                  @click="handleToggleReplies"
                  class="flex items-center gap-2 text-sm text-base-content/60 hover:text-primary transition-all duration-200"
                >
                  <PhCaretDown
                    :size="16"
                    class="transition-transform duration-200"
                    :class="{ 'rotate-180': showReplies }"
                  />
                  <span class="font-medium">{{ comment.replyCount }} 条回复</span>
                </button>
              </slot>
            </div>

            <!-- 回复表单区域 -->
            <div
              v-if="replyingTo === comment.id"
              class="mt-4 p-4 bg-base-100/80 rounded-xl border border-base-300/50 backdrop-blur-sm"
            >
              <slot
                name="reply-form"
                :comment="comment"
                :reply-content="replyContent"
                :submitting="submitting"
                :on-submit="handleCreateReply"
                :on-cancel="cancelReply"
              >
                <div class="space-y-3">
                  <textarea
                    v-model="replyContent"
                    placeholder="写下你的回复..."
                    class="w-full p-3 bg-base-200 rounded-lg border border-base-300/50 focus:border-primary focus:outline-none resize-none"
                    rows="3"
                  ></textarea>
                  <div class="flex justify-end gap-2">
                    <button
                      @click="cancelReply"
                      class="px-4 py-2 text-sm text-base-content/60 hover:text-base-content transition-colors duration-200"
                    >
                      取消
                    </button>
                    <button
                      @click="handleCreateReply(replyContent)"
                      :disabled="!replyContent.trim() || submitting"
                      class="px-4 py-2 text-sm bg-primary text-primary-content rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                    >
                      {{ submitting ? '发送中...' : '发送' }}
                    </button>
                  </div>
                </div>
              </slot>
            </div>
          </div>
        </div>
      </slot>
    </div>

    <!-- 回复列表区域 - 完全可自定义 -->
    <div
      v-if="showRepliesSection && replies && replies.length > 0 && showReplies"
      :class="repliesClass"
    >
      <slot name="replies" v-bind="slotProps" :handlers="eventHandlers">
        <!-- 默认回复列表 -->
        <div
          v-for="reply in replies"
          :key="reply.id"
          class="reply-item bg-base-100/50 rounded-xl p-4 border border-base-300/20 hover:bg-base-100/80 transition-colors duration-200"
        >
          <div class="flex gap-3">
            <slot name="reply-avatar" :author="reply.author">
              <div
                v-if="reply.author.avatar"
                class="w-8 h-8 rounded-full overflow-hidden border border-base-300/50 cursor-pointer"
                @click="handleReplyClick(reply)"
              >
                <img
                  :src="reply.author.avatar"
                  :alt="reply.author.name"
                  class="w-full h-full object-cover"
                />
              </div>
              <div
                v-else
                class="w-8 h-8 bg-gradient-to-br from-secondary to-accent rounded-full flex items-center justify-center text-secondary-content font-semibold text-sm cursor-pointer"
                @click="handleReplyClick(reply)"
              >
                {{ reply.author.name.charAt(0).toUpperCase() }}
              </div>
            </slot>

            <div class="flex-1 min-w-0">
              <div class="flex items-center gap-2 mb-1">
                <h5 class="font-medium text-base-content text-sm">
                  {{ reply.author.name }}
                </h5>
                <time class="text-xs text-base-content/60">{{ formatTime(reply.createdAt) }}</time>
              </div>
              <div class="prose prose-sm max-w-none mb-2">
                <div v-html="reply.content" class="reply-content"></div>
              </div>
              <div class="flex items-center gap-3">
                <button
                  @click="handleToggleLike"
                  class="flex items-center gap-1 text-xs transition-colors duration-200"
                  :class="
                    reply.isLiked ? 'text-red-500' : 'text-base-content/60 hover:text-red-500'
                  "
                >
                  <PhHeart :size="12" :class="{ 'ph-fill': reply.isLiked }" />
                  {{ reply.likes }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多回复 -->
        <div v-if="hasMoreReplies" class="text-center pt-2">
          <button
            @click="handleLoadMoreReplies"
            class="text-sm text-primary hover:text-primary/80 transition-colors duration-200"
          >
            加载更多回复
          </button>
        </div>
      </slot>
    </div>
  </div>
</template>

<style scoped>
.comment-item {
  animation: fadeInUp 0.4s ease-out;
}

.comment-item.animation-enabled {
  animation: fadeInUp 0.4s ease-out;
}

.comment-item.hover-enabled:hover {
  /* 悬停效果由父组件控制 */
  transform: translateY(-1px);
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.comment-content {
  line-height: 1.7;
}

.comment-content :deep(p) {
  margin: 0.5rem 0;
}

.comment-content :deep(code) {
  background: hsl(var(--b2));
  padding: 0.2rem 0.4rem;
  border-radius: 0.25rem;
  font-size: 0.875rem;
  color: hsl(var(--bc));
}

.comment-content :deep(pre) {
  background: hsl(var(--b2));
  padding: 1rem;
  border-radius: 0.5rem;
  overflow-x: auto;
  margin: 1rem 0;
  border: 1px solid hsl(var(--b3));
}

.comment-content :deep(blockquote) {
  border-left: 4px solid hsl(var(--p));
  padding-left: 1rem;
  margin: 1rem 0;
  color: hsl(var(--bc) / 0.8);
  font-style: italic;
}

.comment-content :deep(a) {
  color: hsl(var(--p));
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: border-color 0.2s ease;
}

.comment-content :deep(a:hover) {
  border-bottom-color: hsl(var(--p));
}

.reply-content {
  line-height: 1.6;
}

.reply-content :deep(p) {
  margin: 0.25rem 0;
}

.reply-content :deep(code) {
  background: hsl(var(--b2));
  padding: 0.1rem 0.3rem;
  border-radius: 0.25rem;
  font-size: 0.75rem;
}

.reply-content :deep(pre) {
  background: hsl(var(--b2));
  padding: 0.5rem;
  border-radius: 0.25rem;
  overflow-x: auto;
  margin: 0.5rem 0;
  font-size: 0.75rem;
}

/* 点击外部关闭下拉菜单 */
.comment-item:focus-within .show-more-actions {
  display: block;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comment-item {
    padding: 0.5rem;
  }

  .comment-content {
    font-size: 0.875rem;
  }

  .reply-content {
    font-size: 0.75rem;
  }
}
</style>
